package cn.tedu.search.controller;

import com.jt.common.pojo.Product;
import com.jt.common.utils.MapperUtil;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequestBuilder;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.client.AdminClient;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@RestController
public class CreateIndexController {
    @Autowired
    TransportClient client;

    @Autowired
    RestTemplate restTemplate;

    /**
     * 注入mapper对象，获取商品数据的list
     * 按照新增文档的说明，将所有商品的信息转化为json存储在elasticsearch的集群中
     */
    @RequestMapping("/create")
    public String createIndex(String indexName, String typeName) {
        // 调用微服务获取商品数据
        String url = "http://productservice/product/manage/queryAllProduct";
        List<Product> productList = null;
        try {
            Product[] products = restTemplate.getForObject(url, Product[].class);
            productList = new ArrayList<>();
            for (Product product : products)
                productList.add(product);
        } catch (RestClientException restClientException) {
            restClientException.printStackTrace();
        }

        // 封装成json，client发起请求写入es索引
        try {
            // 判断索引是否存在，不存在则创建
            AdminClient admin = client.admin();
            IndicesAdminClient indices = admin.indices();
            IndicesExistsRequestBuilder request = indices.prepareExists(indexName);
            IndicesExistsResponse response = request.get();
            if (!response.isExists()) {
                // 创建索引
                indices.prepareCreate(indexName).get();
            }
            for (Product product : productList) {
                // 转化对象为json
                String productJson = MapperUtil.MP.writeValueAsString(product);
                // 调用client的api生成request，将json包装
                IndexRequestBuilder request1 = client.prepareIndex(indexName, typeName, product.getProductId());
                // productJson放到request的source数据中
                request1.setSource(productJson);
                request1.get();
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
    }
}
